/*
 * Copyright 1999-2011 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dromara.common.core.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.multi.RowKeyTable;
import cn.hutool.core.map.multi.Table;
import jodd.util.PropertiesUtil;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Function;

public class CollectionUtils extends org.springframework.util.CollectionUtils {

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> List<T> sort(List<T> list) {
        if (list != null && list.size() > 0) {
            Collections.sort((List) list);
        }
        return list;
    }

    private static final Comparator<String> SIMPLE_NAME_COMPARATOR = new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            if (s1 == null && s2 == null) {
                return 0;
            }
            if (s1 == null) {
                return -1;
            }
            if (s2 == null) {
                return 1;
            }
            int i1 = s1.lastIndexOf('.');
            if (i1 >= 0) {
                s1 = s1.substring(i1 + 1);
            }
            int i2 = s2.lastIndexOf('.');
            if (i2 >= 0) {
                s2 = s2.substring(i2 + 1);
            }
            return s1.compareToIgnoreCase(s2);
        }
    };

    public static List<String> sortSimpleName(List<String> list) {
        if (list != null && list.size() > 0) {
            Collections.sort(list, SIMPLE_NAME_COMPARATOR);
        }
        return list;
    }

    public static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator) {
        if (list == null) {
            return null;
        }
        Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, List<String>> entry : list.entrySet()) {
            result.put(entry.getKey(), split(entry.getValue(), separator));
        }
        return result;
    }

    public static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator) {
        if (map == null) {
            return null;
        }
        Map<String, List<String>> result = new HashMap<String, List<String>>();
        for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
            result.put(entry.getKey(), join(entry.getValue(), separator));
        }
        return result;
    }

    public static Map<String, String> split(List<String> list, String separator) {
        if (list == null) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        if (list == null || list.size() == 0) {
            return map;
        }
        for (String item : list) {
            int index = item.indexOf(separator);
            if (index == -1) {
                map.put(item, "");
            } else {
                map.put(item.substring(0, index), item.substring(index + 1));
            }
        }
        return map;
    }

    public static List<String> join(Map<String, String> map, String separator) {
        if (map == null) {
            return null;
        }
        List<String> list = new ArrayList<String>();
        if (map == null || map.size() == 0) {
            return list;
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value == null || value.length() == 0) {
                list.add(key);
            } else {
                list.add(key + separator + value);
            }
        }
        return list;
    }

    public static String join(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (String ele : list) {
            if (sb.length() > 0) {
                sb.append(separator);
            }
            sb.append(ele);
        }
        return sb.toString();
    }

    public static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2) {
        if (map1 == null && map2 == null) {
            return true;
        }
        if (map1 == null || map2 == null) {
            return false;
        }
        if (map1.size() != map2.size()) {
            return false;
        }
        for (Map.Entry<?, ?> entry : map1.entrySet()) {
            Object key = entry.getKey();
            Object value1 = entry.getValue();
            Object value2 = map2.get(key);
            if (!objectEquals(value1, value2)) {
                return false;
            }
        }
        return true;
    }

    private static boolean objectEquals(Object obj1, Object obj2) {
        if (obj1 == null && obj2 == null) {
            return true;
        }
        if (obj1 == null || obj2 == null) {
            return false;
        }
        return obj1.equals(obj2);
    }

    public static Map<String, String> toStringMap(String... pairs) {
        Map<String, String> parameters = new HashMap<String, String>();
        if (pairs.length > 0) {
            if (pairs.length % 2 != 0) {
                throw new IllegalArgumentException("pairs must be even.");
            }
            for (int i = 0; i < pairs.length; i = i + 2) {
                parameters.put(pairs[i], pairs[i + 1]);
            }
        }
        return parameters;
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> toMap(Object... pairs) {
        Map<K, V> ret = new HashMap<K, V>();
        if (pairs == null || pairs.length == 0) return ret;

        if (pairs.length % 2 != 0) {
            throw new IllegalArgumentException("Map pairs can not be odd number.");
        }
        int len = pairs.length / 2;
        for (int i = 0; i < len; i++) {
            ret.put((K) pairs[2 * i], (V) pairs[2 * i + 1]);
        }
        return ret;
    }

    public static <K> Collection<K> toList(Function<K, Boolean> check, Object... pairs) {
        Collection<K> ret = new ArrayList<>();
        if (pairs == null || pairs.length == 0) {
            return ret;
        }


        for (int i = 0; i < pairs.length; i++) {
            if (check.apply((K) pairs[i])) {
                ret.add((K) pairs[i]);
            }
        }
        return ret;
    }

    public static <K> Collection<K> toSet(Object... pairs) {
        Collection<K> ret = new HashSet<K>();
        if (pairs == null || pairs.length == 0) return ret;

        for (int i = 0; i < pairs.length; i++) {
            ret.add((K) pairs[i]);
        }
        return ret;
    }

    /**
     * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
     *
     * @param collection        来源集合.
     * @param keyPropertyName   要提取为Map中的Key值的属性名.
     * @param valuePropertyName 要提取为Map中的Value值的属性名.
     */
    public static Map extractToMap(final Collection collection, final String keyPropertyName,
                                   final String valuePropertyName) {
        Map map = new HashMap(collection.size());

        try {
            for (Object obj : collection) {
                map.put(BeanUtil.getProperty(obj, keyPropertyName),
                    BeanUtil.getProperty(obj, valuePropertyName));
            }
        } catch (Exception e) {
//            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return map;
    }

    /**
     * 提取集合中的对象的两个属性(通过Getter函数), 组合成List.
     *
     * @param collection 来源集合.
     * @param propertys  要提取为Map中的Key值的属性名.
     */
    public static List<Map<String, Object>> extractToList(final Collection collection, final String... propertys) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(collection.size());

        try {
            for (Object obj : collection) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (String property : propertys) {
                    map.put(property, BeanUtil.getProperty(obj, property));
                }
                list.add(map);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return list;
    }

    /**
     * 提取集合中的对象的两个属性(通过Getter函数), 组合成List. 专给登录使用，手机里面的id是关键字必须修改名字
     *
     * @param collection        来源集合.
     * @param keyPropertyName   要提取为Map中的Key值的属性名.
     * @param valuePropertyName 要提取为Map中的Value值的属性名.
     */
    public static List<Map<Object, Object>> extractToList(final Collection collection, final String keyPropertyName,
                                                          final String valuePropertyName, final String keyName, BiFunction<Map<Object, Object>, Object, Boolean> check) {
        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>(collection.size());

        try {
            Map<Object, Object> keys = new HashMap<Object, Object>();
            for (Object obj : collection) {
                Map<Object, Object> map = new HashMap<Object, Object>();
                Object key = BeanUtil.getProperty(obj, keyPropertyName);
                if (check.apply(keys, key)) {
                    map.put(keyName, BeanUtil.getProperty(obj, keyPropertyName));
                    keys.put(keyName, BeanUtil.getProperty(obj, keyPropertyName));
                    map.put(valuePropertyName, BeanUtil.getProperty(obj, valuePropertyName));
                    list.add(map);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
//            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    public static List<Map<Object, Object>> extractToList(final Collection collection, final String keyPropertyName,
                                                          final String valuePropertyName, final String keyName) {
        BiFunction check = new BiFunction<Map<Object, Object>, Object, Boolean>() {
            @Override
            public Boolean apply(Map<Object, Object> stringObjectMap, Object o) {
                return true;
            }
        };
        return extractToList(collection, keyPropertyName, valuePropertyName, keyName, check);
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static List extractToList(final Collection collection, final String propertyName) {
        List list = new ArrayList(collection.size());

        try {
            for (Object obj : collection) {
                list.add(BeanUtil.getProperty(obj, propertyName));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
//            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    public static Set extractToSet(final Collection collection, final String propertyName) {
        Set set = new HashSet(collection.size());

        try {
            for (Object obj : collection) {
                set.add(BeanUtil.getProperty(obj, propertyName));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
//            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return set;
    }

    public static String extractAndConvertToString(final Collection collection, final String propertyName, final String separator) {
        String propertyNames;
        List<String> propertyList = extractToList(collection, propertyName);
        propertyNames = convertToString(propertyList, separator);
        return propertyNames;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成Map.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static Map extractToMap(final Collection collection, final String propertyName) {
        Map m = new HashMap();

        try {
            for (Object obj : collection) {
                m.put(BeanUtil.getProperty(obj, propertyName), obj);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
//            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return m;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     * @param separator    分隔符.
     */
    public static String extractToString(final Collection collection, final String propertyName, final String separator) {
        List list = extractToList(collection, propertyName);
        return StringUtils.join(list, separator);
    }

    /**
     * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
     */
    public static String convertToString(final Collection collection, final String separator) {
        return StringUtils.join(collection, separator);
    }

    /**
     * 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix，后面加入postfix，如<div>mymessage</div>。
     */
    public static String convertToString(final Collection collection, final String prefix, final String postfix) {
        StringBuilder builder = new StringBuilder();
        for (Object o : collection) {
            builder.append(prefix).append(o).append(postfix);
        }
        return builder.toString();
    }

    /**
     * 判断是否为空.
     */
    public static boolean isEmpty(Collection collection) {
        return ((collection == null) || collection.isEmpty());
    }

    /**
     * 取得Collection的第一个元素，如果collection为空返回null.
     */
    public static <T> T getFirst(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        return collection.iterator().next();
    }

    /**
     * 获取Collection的最后一个元素 ，如果collection为空返回null.
     */
    public static <T> T getLast(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        // 当类型为List时，直接取得最后一个元素 。
        if (collection instanceof List) {
            List<T> list = (List<T>) collection;
            return list.get(list.size() - 1);
        }

        // 其他类型通过iterator滚动到最后一个元素.
        Iterator<T> iterator = collection.iterator();
        while (true) {
            T current = iterator.next();
            if (!iterator.hasNext()) {
                return current;
            }
        }
    }

    /**
     * 返回a+b的新List.
     */
    public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
        List<T> result = new ArrayList<T>(a);
        result.addAll(b);
        return result;
    }

    /**
     * 返回a-b的新List.
     */
    public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
        List<T> list = new ArrayList<T>(a);
        for (T element : b) {
            list.remove(element);
        }

        return list;
    }

    /**
     * 返回a与b的交集的新List.
     */
    public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
        List<T> list = new ArrayList<T>();

        for (T element : a) {
            if (b.contains(element)) {
                list.add(element);
            }
        }
        return list;
    }


    public static boolean isArray(Class<?> aClass) {
        return aClass.isArray();
    }

    public static boolean isCollection(Class<?> aClass) {
        return Collection.class.isAssignableFrom(aClass);
    }

    public static boolean isList(Class<?> aClass) {
        return List.class.isAssignableFrom(aClass);
    }

    public static boolean isSet(Class<?> aClass) {
        return Set.class.isAssignableFrom(aClass);
    }

    public static boolean isPrimitiveArray(Class<?> aClass) {
        return aClass.isArray() && aClass.getComponentType().isPrimitive();
    }

    public static int getLengthOfCollection(Object value) {
        if (isArray(value.getClass())) {
            return Array.getLength(value);
        } else {
            return ((Collection<?>) value).size();
        }
    }

    public static Object getValueFromCollection(Object collection, int index) {
        if (isArray(collection.getClass())) {
            return Array.get(collection, index);
        } else {
            return ((Collection<?>) collection).toArray()[index];
        }
    }

    public static <T extends Set<?>> Set<?> createNewSet(Class<T> destType) {
        Set<Object> result;
        if (SortedSet.class.isAssignableFrom(destType)) {
            result = new TreeSet<Object>();
        } else {
            result = new HashSet<Object>();
        }
        return result;
    }

    public static <T extends Set<?>> Set<?> createNewSet(Class<T> destSetType, Collection<?> srcValue) {
        Set<Object> result = (Set<Object>) createNewSet(destSetType);
        if (srcValue != null) {
            result.addAll(srcValue);
        }
        return result;
    }

    public static <T> Object convertListToArray(List<T> list, Class<T> destEntryType) {

        Object outArray = Array.newInstance(destEntryType, list.size());
        int count = 0;
        int size = list.size();
        for (int i = 0; i < size; i++) {
            Object element = list.get(i);
            Array.set(outArray, count, element);
            count++;
        }
        return outArray;
//        if (destEntryType.isPrimitive())
//            return outArray;
//        else {
//            return outArray;
//        }
    }

    public static List<Object> convertPrimitiveArrayToList(Object primitiveArray) {
        int length = Array.getLength(primitiveArray);
        List<Object> result = new ArrayList<Object>(length);

        // wrap and copy elements
        for (int i = 0; i < length; i++) {
            result.add(Array.get(primitiveArray, i));
        }
        return result;
    }


    public static <E> Set<E> intersection(final Set<E> set1, final Set<?> set2) {
        Set<E> intersection = new HashSet<E>(set1);
        intersection.retainAll(set2);
        return intersection;
    }

    /**
     * Check whether the given Iterator contains the given element.
     *
     * @param iterator the Iterator to check
     * @param element  the element to look for
     * @return {@code true} if found, {@code false} else
     */
    public static boolean contains(Iterator<?> iterator, Object element) {
        if (iterator != null) {
            while (iterator.hasNext()) {
                Object candidate = iterator.next();
                if (ObjectUtils.nullSafeEquals(candidate, element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Check whether the given Enumeration contains the given element.
     *
     * @param enumeration the Enumeration to check
     * @param element     the element to look for
     * @return {@code true} if found, {@code false} else
     */
    public static boolean contains(Enumeration<?> enumeration, Object element) {
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                Object candidate = enumeration.nextElement();
                if (ObjectUtils.nullSafeEquals(candidate, element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Check whether the given Collection contains the given element instance.
     * <p>Enforces the given instance to be present, rather than returning
     * {@code true} for an equal element as well.
     *
     * @param collection the Collection to check
     * @param element    the element to look for
     * @return {@code true} if found, {@code false} else
     */
    public static boolean containsInstance(Collection<?> collection, Object element) {
        if (collection != null) {
            for (Object candidate : collection) {
                if (candidate == element) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Return {@code true} if any element in '{@code candidates}' is
     * contained in '{@code source}'; otherwise returns {@code false}.
     *
     * @param source     the source Collection
     * @param candidates the candidates to search for
     * @return whether any of the candidates has been found
     */
    public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
        if (isEmpty(source) || isEmpty(candidates)) {
            return false;
        }
        for (Object candidate : candidates) {
            if (source.contains(candidate)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return the first element in '{@code candidates}' that is contained in
     * '{@code source}'. If no element in '{@code candidates}' is present in
     * '{@code source}' returns {@code null}. Iteration order is
     * {@link Collection} implementation specific.
     *
     * @param source     the source Collection
     * @param candidates the candidates to search for
     * @return the first present object, or {@code null} if not found
     */
    @SuppressWarnings("unchecked")
    public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
        if (isEmpty(source) || isEmpty(candidates)) {
            return null;
        }
        for (Object candidate : candidates) {
            if (source.contains(candidate)) {
                return (E) candidate;
            }
        }
        return null;
    }

    /**
     * Find a single value of the given type in the given Collection.
     *
     * @param collection the Collection to search
     * @param type       the type to look for
     * @return a value of the given type found if there is a clear match,
     * or {@code null} if none or more than one such value found
     */
    @SuppressWarnings("unchecked")
    public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
        if (isEmpty(collection)) {
            return null;
        }
        T value = null;
        for (Object element : collection) {
            if (type == null || type.isInstance(element)) {
                if (value != null) {
                    // More than one value found... no clear single value.
                    return null;
                }
                value = (T) element;
            }
        }
        return value;
    }

    /**
     * Find a single value of one of the given types in the given Collection:
     * searching the Collection for a value of the first type, then
     * searching for a value of the second type, etc.
     *
     * @param collection the collection to search
     * @param types      the types to look for, in prioritized order
     * @return a value of one of the given types found if there is a clear match,
     * or {@code null} if none or more than one such value found
     */
    public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
        if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
            return null;
        }
        for (Class<?> type : types) {
            Object value = findValueOfType(collection, type);
            if (value != null) {
                return value;
            }
        }
        return null;
    }

    /**
     * Determine whether the given Collection only contains a single unique object.
     *
     * @param collection the Collection to check
     * @return {@code true} if the collection contains a single reference or
     * multiple references to the same instance, {@code false} else
     */
    public static boolean hasUniqueObject(Collection<?> collection) {
        if (isEmpty(collection)) {
            return false;
        }
        boolean hasCandidate = false;
        Object candidate = null;
        for (Object elem : collection) {
            if (!hasCandidate) {
                hasCandidate = true;
                candidate = elem;
            } else if (candidate != elem) {
                return false;
            }
        }
        return true;
    }

    /**
     * Find the common element type of the given Collection, if any.
     *
     * @param collection the Collection to check
     * @return the common element type, or {@code null} if no clear
     * common type has been found (or the collection was empty)
     */
    public static Class<?> findCommonElementType(Collection<?> collection) {
        if (isEmpty(collection)) {
            return null;
        }
        Class<?> candidate = null;
        for (Object val : collection) {
            if (val != null) {
                if (candidate == null) {
                    candidate = val.getClass();
                } else if (candidate != val.getClass()) {
                    return null;
                }
            }
        }
        return candidate;
    }

    /**
     * Marshal the elements from the given enumeration into an array of the given type.
     * Enumeration elements must be assignable to the type of the given array. The array
     * returned will be a different instance than the array given.
     */
    public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
        ArrayList<A> elements = new ArrayList<A>();
        while (enumeration.hasMoreElements()) {
            elements.add(enumeration.nextElement());
        }
        return elements.toArray(array);
    }


    /**
     * Adapt an enumeration to an iterator.
     *
     * @param enumeration the enumeration
     * @return the iterator
     */
    public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) {
        return new EnumerationIterator<E>(enumeration);
    }

    /**
     * Iterator wrapping an Enumeration.
     */
    private static class EnumerationIterator<E> implements Iterator<E> {

        private final Enumeration<E> enumeration;

        public EnumerationIterator(Enumeration<E> enumeration) {
            this.enumeration = enumeration;
        }

        @Override
        public boolean hasNext() {
            return this.enumeration.hasMoreElements();
        }

        @Override
        public E next() {
            return this.enumeration.nextElement();
        }

        @Override
        public void remove() throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Not supported");
        }
    }

    /**
     * 判断一个数组是否是空数组
     *
     * @param ary 数组
     * @return null 或者空数组都为 true 否则为 false
     */
    public static <T> boolean isEmptyArray(T[] ary) {
        return null == ary || ary.length == 0;
    }

    /**
     * 较方便的创建一个列表，比如：
     *
     * <pre>
     * List&lt;Pet&gt; pets = Lang.list(pet1, pet2, pet3);
     * </pre>
     * <p>
     * 注，这里的 List，是 ArrayList 的实例
     *
     * @param eles 可变参数
     * @return 列表对象
     */
    public static <T> ArrayList<T> list(T... eles) {
        ArrayList<T> list = new ArrayList<T>(eles.length);
        for (T ele : eles)
            list.add(ele);
        return list;
    }

    /**
     * 创建一个 Hash 集合
     *
     * @param eles 可变参数
     * @return 集合对象
     */
    public static <T> Set<T> set(T... eles) {
        Set<T> set = new HashSet<T>();
        for (T ele : eles)
            set.add(ele);
        return set;
    }

    /**
     * 将多个数组，合并成一个数组。如果这些数组为空，则返回 null
     *
     * @param arys 数组对象
     * @return 合并后的数组对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] merge(T[]... arys) {
        Queue<T> list = new LinkedList<T>();
        for (T[] ary : arys) {
            if (null != ary) {
                for (T e : ary) {
                    if (null != e) {
                        list.add(e);
                    }
                }
            }
        }
        if (list.isEmpty()) {
            return null;
        }
        Class<T> type = (Class<T>) list.peek().getClass();
        return list.toArray((T[]) Array.newInstance(type, list.size()));
    }

    /**
     * 将一个对象添加成为一个数组的第一个元素，从而生成一个新的数组
     *
     * @param e    对象
     * @param eles 数组
     * @return 新数组
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] arrayFirst(T e, T[] eles) {
        try {
            if (null == eles || eles.length == 0) {
                T[] arr = (T[]) Array.newInstance(e.getClass(), 1);
                arr[0] = e;
                return arr;
            }
            T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1);
            arr[0] = e;
            for (int i = 0; i < eles.length; i++) {
                arr[i + 1] = eles[i];
            }
            return arr;
        } catch (NegativeArraySizeException e1) {
            throw StringUtils.wrapThrow(e1);
        }
    }

    /**
     * 将一个对象添加成为一个数组的最后一个元素，从而生成一个新的数组
     *
     * @param e    对象
     * @param eles 数组
     * @return 新数组
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] arrayLast(T[] eles, T e) {
        try {
            if (null == eles || eles.length == 0) {
                T[] arr = (T[]) Array.newInstance(e.getClass(), 1);
                arr[0] = e;
                return arr;
            }
            T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1);
            for (int i = 0; i < eles.length; i++) {
                arr[i] = eles[i];
            }
            arr[eles.length] = e;
            return arr;
        } catch (NegativeArraySizeException e1) {
            throw StringUtils.wrapThrow(e1);
        }
    }


    private static final String KV_SPLIT = "=";

    private static final String PAIR_SPLIT = "&";

    /**
     * Encode map to string
     *
     * @param map origin map
     * @return String string
     */
    public static String encodeMap(Map<String, String> map) {
        if (map == null) {
            return null;
        }
        if (map.isEmpty()) {
            return StringUtils.EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey()).append(KV_SPLIT).append(entry.getValue()).append(PAIR_SPLIT);
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * Decode string to map
     *
     * @param data data
     * @return map map
     */
    public static Map<String, String> decodeMap(String data) {
        if (data == null) {
            return null;
        }
        Map<String, String> map = new ConcurrentHashMap<>();
        if (StringUtils.isBlank(data)) {
            return map;
        }
        String[] kvPairs = data.split(PAIR_SPLIT);
        if (kvPairs.length == 0) {
            return map;
        }
        for (String kvPair : kvPairs) {
            if (StringUtils.isEmpty(kvPair)) {
                continue;
            }
            String[] kvs = kvPair.split(KV_SPLIT);
            if (kvs.length != 2) {
                continue;
            }
            map.put(kvs[0], kvs[1]);
        }
        return map;
    }

    /**
     * To upper list list.
     *
     * @param sourceList the source list
     * @return the list
     */
    public static List<String> toUpperList(List<String> sourceList) {
        if (isEmpty(sourceList)) {
            return sourceList;
        }
        List<String> destList = new ArrayList<>(sourceList.size());
        for (String element : sourceList) {
            if (null != element) {
                destList.add(element.toUpperCase());
            } else {
                destList.add(null);
            }
        }
        return destList;
    }

    public static int countMapValues(Map<?, ?> map) {
        int total = 0;
        if (map != null && map.size() > 0) {
            for (Object value : map.values()) {
                if (value != null) {
                    if (value instanceof Number) {
                        total += ((Number) value).intValue();
                    } else if (value.getClass().isArray()) {
                        total += Array.getLength(value);
                    } else if (value instanceof Collection) {
                        total += ((Collection<?>) value).size();
                    } else if (value instanceof Map) {
                        total += ((Map<?, ?>) value).size();
                    } else {
                        total += 1;
                    }
                }
            }
        }
        return total;
    }


    /**
     * Check whether the given Array contains the given element.
     *
     * @param array   the Array to check
     * @param element the element to look for
     * @param <T>     The generic tag
     * @return {@code true} if found, {@code false} else
     */
    public static <T> boolean contains(@Nullable T[] array, final T element) {
        if (array == null) {
            return false;
        }
        return Arrays.stream(array).anyMatch(x -> ObjectUtils.nullSafeEquals(x, element));
    }

    /**
     * 对象是否为数组对象
     *
     * @param obj 对象
     * @return 是否为数组对象，如果为{@code null} 返回false
     */
    public static boolean isArray(Object obj) {
        if (null == obj) {
            return false;
        }
        return obj.getClass().isArray();
    }

    /**
     * Determine whether the given Collection is not empty:
     * i.e. {@code null} or of zero length.
     *
     * @param coll the Collection to check
     * @return boolean
     */
    public static boolean isNotEmpty(@Nullable Collection<?> coll) {
        return !CollectionUtils.isEmpty(coll);
    }

    public static boolean isNotEmpty(@Nullable Object[] coll) {
        return coll != null && coll.length > 0;
    }

    /**
     * Determine whether the given Map is not empty:
     * i.e. {@code null} or of zero length.
     *
     * @param map the Map to check
     * @return boolean
     */
    public static boolean isNotEmpty(@Nullable Map<?, ?> map) {
        return !CollectionUtils.isEmpty(map);
    }


    public static <T> List<List<T>> partition(List<T> source, int partitionSize) {
        List<List<T>> result = new ArrayList<>();
        if (source == null || source.size() <= partitionSize) {
            result.add(source);
            return result;
        }
        int size = source.size();
        int offset = 0;
        while (offset < size) {
            List<T> part = new ArrayList<>();
            result.add(part);
            int endIndex = offset + partitionSize;
            endIndex = endIndex > size ? size : endIndex;
            for (int i = offset; i < endIndex; i++) {
                part.add(source.get(i));
            }
            offset += endIndex;
        }
        return result;
    }

    public static <T> List<Set<T>> partition(Set<T> source, int partitionSize) {
        List<Set<T>> result = new ArrayList<>();
        if (source == null || source.size() <= partitionSize) {
            result.add(source);
            return result;
        }
        int size = source.size();
        int offset = 0;
        Iterator<T> iterator = source.iterator();
        while (offset < size && iterator.hasNext()) {
            Set<T> part = new HashSet<>();
            result.add(part);
            int endIndex = offset + partitionSize;
            endIndex = endIndex > size ? size : endIndex;
            for (int i = offset; i < endIndex && iterator.hasNext(); i++) {
                part.add(iterator.next());
            }
            offset += endIndex;
        }
        return result;
    }


    public static <T> List<T> join(List<T>... source) {
        if (source == null || source.length <= 0) {
            return new ArrayList<>(0);
        }

        List<T> list = new ArrayList<>();
        for (List<T> ts : source) {
            if (ts == null || ts.isEmpty()) {
                continue;
            }
            for (T t : ts) {
                list.add(t);
            }
        }
        return list;
    }

    public static <T> List<T> join(List<List<T>> source) {
        if (source == null || source.size() <= 0) {
            return new ArrayList<>(0);
        }

        List<T> list = new ArrayList<>();
        for (List<T> ts : source) {
            if (ts == null || ts.isEmpty()) {
                continue;
            }
            for (T t : ts) {
                list.add(t);
            }
        }
        return list;
    }

    /**
     * Source 转换成单项
     *
     * @param convert
     * @param source
     * @param <T>
     * @param <S>
     * @return
     */
    public static <T, S> List<T> join(java.util.function.Function<S, T> convert, List<S>... source) {
        if (source == null || source.length <= 0) {
            return new ArrayList<>(0);
        }

        List<T> list = new ArrayList<>();
        for (List<S> s : source) {
            if (s == null) {
                continue;
            }
            for (S s1 : s) {
                T ts = convert.apply(s1);

                list.add(ts);
            }
        }
        return list;
    }

    /**
     * Source 转换成 List
     *
     * @param convert
     * @param source
     * @param <T>
     * @param <S>
     * @return
     */
    public static <T, S> List<T> joinList(java.util.function.Function<S, List<T>> convert, List<S>... source) {
        if (source == null || source.length <= 0) {
            return new ArrayList<>(0);
        }

        List<T> list = new ArrayList<>();
        for (List<S> s : source) {
            if (s == null) {
                continue;
            }
            for (S s1 : s) {
                List<T> ts = convert.apply(s1);
                if (ts == null || ts.isEmpty()) {
                    continue;
                }

                for (T t : ts) {
                    list.add(t);
                }
            }
        }
        return list;
    }

    public static <K, V> Map<K, V> toMap(List<V> source, java.util.function.Function<V, K> keyConvert) {
        if (source == null || source.isEmpty()) {
            return new HashMap<>(0);
        }

        Map<K, V> map = new HashMap<>();
        for (V v : source) {
            K k = keyConvert.apply(v);
            map.put(k, v);
        }
        return map;
    }

    public static <S, K, V> Map<K, V> toMap(List<S> source, java.util.function.Function<S, K> keyConvert, java.util.function.Function<S, V> valueConvert) {
        if (source == null || source.isEmpty()) {
            return new HashMap<>(0);
        }

        Map<K, V> map = new HashMap<>();
        for (S s : source) {
            K k = keyConvert.apply(s);
            V v = valueConvert.apply(s);
            map.put(k, v);
        }
        return map;
    }

    public static <K, V> Map<K, List<V>> toMapList(List<V> source, java.util.function.Function<V, K> keyConvert) {
        if (source == null || source.isEmpty()) {
            return new HashMap<>(0);
        }

        Map<K, List<V>> map = new HashMap<>();
        for (V v : source) {
            K k = keyConvert.apply(v);
            List<V> vs = map.get(k);
            if (vs == null) {
                vs = new ArrayList<>();
                map.put(k, vs);
            }
            vs.add(v);
        }
        return map;
    }

    public static <S, K, V> Map<K, List<V>> toMapList(List<S> source, java.util.function.Function<S, K> keyConvert,
                                                      java.util.function.Function<S, V> valueConvert) {
        if (source == null || source.isEmpty()) {
            return new HashMap<>(0);
        }

        Map<K, List<V>> map = new HashMap<>();
        for (S s : source) {
            K k = keyConvert.apply(s);
            V v = valueConvert.apply(s);
            List<V> vs = map.get(k);
            if (vs == null) {
                vs = new ArrayList<>();
                map.put(k, vs);
            }
            vs.add(v);
        }
        return map;
    }

    public static <R, C, V> Table<R, C, V> toGoogleTable(
        List<V> source,
        java.util.function.Function<V, R> rowKeyConvert,
        java.util.function.Function<V, C> columnKeyConvert) {
        Table<R, C, V> table = new RowKeyTable<>();
        if (source == null || source.isEmpty()) {
            return table;
        }

        for (V s : source) {
            if (s == null) {
                continue;
            }

            R rowKey = rowKeyConvert.apply(s);
            C columnKey = columnKeyConvert.apply(s);
            table.put(rowKey, columnKey, s);
        }
        return table;
    }

    // @Nullable Object rowKey, @Nullable Object columnKey
    public static <S, R, C, V> Table<R, C, V> toGoogleTable(
        List<S> source,
        java.util.function.Function<S, R> rowKeyConvert,
        java.util.function.Function<S, C> columnKeyConvert,
        java.util.function.Function<S, V> valueKeyConvert) {
        Table<R, C, V> table = new RowKeyTable<>();
        if (source == null || source.isEmpty()) {
            return table;
        }

        for (S s : source) {
            if (s == null) {
                continue;
            }

            R rowKey = rowKeyConvert.apply(s);
            C columnKey = columnKeyConvert.apply(s);
            V value = valueKeyConvert.apply(s);
            table.put(rowKey, columnKey, value);
        }
        return table;
    }
}
